//
//  MusicStoreView2.swift
//  GFQM
//
//  Created by iSolar on 2017/5/4.
//  Copyright © 2017年 iSolar. All rights reserved.
//

import UIKit

class MusicStoreView2: UIView, UIScrollViewDelegate {

    let scrollV = LMJ_MyScrollView()
    let page = UIPageControl()


    //MARK:- 构造函数
    override init(frame: CGRect) {
        super.init(frame: frame)
        creatScrollView()
        creatTimer()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    let imageNames = ["1","2","3"]
    func creatScrollView() {
        let view = UIView(frame: CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: 140))
        addSubview(view)
        view.backgroundColor = UIColor.yellow
        view.addSubview(scrollV)
        scrollV.backgroundColor = UIColor.purple
        scrollV.frame = view.frame
        scrollV.creatMyScrollView(imageName: imageNames, height: 140)
        let pageW: CGFloat = 80
        let pageH: CGFloat = 20
        page.bounds = CGRect(x: 0, y: 0, width: pageW, height: pageH)
        page.center = CGPoint(x: UIScreen.main.bounds.width/2, y: 130)
        page.numberOfPages = imageNames.count
        page.pageIndicatorTintColor = UIColor.lightGray
        page.currentPageIndicatorTintColor = UIColor.blue
        //将小白点放到scr之上
        view.insertSubview(page, aboveSubview: scrollV)
    }

    //创建轮播图定时器
    func creatTimer() {
        let  timer =  Timer.scheduledTimer(timeInterval: 3, target: self, selector: #selector(self.timerManager), userInfo: nil, repeats: true)

        //这句话实现多线程，如果你的ScrollView是作为TableView的headerView的话，在拖动tableView的时候让轮播图仍然能轮播就需要用到这句话
        RunLoop.current.add(timer, forMode: RunLoopMode.commonModes)

    }

    //创建定时器管理者
    func timerManager() {
        //设置偏移量scr.setContentOffset(CGPointMake(scr.contentOffset.x + width, 0), animated: true)
        //当偏移量达到最后一张的时候，让偏移量置零
        if scrollV.contentOffset.x == CGFloat(scrollV.frame.size.width) * CGFloat(imageNames.count) {
            scrollV.contentOffset = CGPoint(x:0, y:0)
        }

    }

    var cnt = 0
    func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
        let cPage = scrollV.contentOffset.x / scrollV.frame.size.width
        page.currentPage = Int(cPage)
        cnt = Int(cPage)
    }

    //自动播放时，调用该方法
    func scrollViewDidEndScrollingAnimation(_ scrollView: UIScrollView) {
        cnt += 1
        page.currentPage = cnt % imageNames.count
    }

}
